/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * BounderyUI.java
 *
 * Created on Mar 31, 2011, 6:31:42 PM
 */

package Taxi;

import Taxi.db.Database;
import Taxi.db.OperationsDAO;
import Taxi.model.Operation;
import Taxi.util.HelperUtil;
import java.sql.SQLException;
import java.text.ParseException;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import org.jdesktop.beansbinding.Binding;

/**
 *
 * @author U24022
 */
public class BounderyUI extends javax.swing.JFrame {

    private OperationsDAO operationsDAO = new OperationsDAO();

    private static final String STATUS_MSG1 = "Enter Driver & 'From Date' (optional), then click Get Records to start";
    private static final String STATUS_MSG2 = "Double-click on the rows to edit";
    private static final String STATUS_MSG3 = "Click Save Changes to save new values";

    /** Creates new form BounderyUI */
    public BounderyUI() {
        initComponents();
        statusLabel.setText(STATUS_MSG1);
        saveChangesB.setEnabled(false);
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        bindingGroup = new org.jdesktop.beansbinding.BindingGroup();

        boundaryList = org.jdesktop.observablecollections.ObservableCollections.observableList(new LinkedList<Taxi.model.Operation>());
        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        getRecordsB = new javax.swing.JButton();
        driverTF = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        fromDateFTF = new javax.swing.JFormattedTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        boundaryTable = new javax.swing.JTable();
        jLabel2 = new javax.swing.JLabel();
        totalDeficitLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        saveChangesB = new javax.swing.JButton();
        statusLabel = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Boundary Manager");

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder("Boundery Manager"));

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)), "Driver Search"));

        getRecordsB.setText("Get Records");
        getRecordsB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                getRecordsBActionPerformed(evt);
            }
        });

        driverTF.setText("Mang Jose");
        driverTF.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                driverTFActionPerformed(evt);
            }
        });

        jLabel1.setText("Driver:");

        jLabel3.setText("From Date: mm-dd-yy");

        fromDateFTF.setFormatterFactory(new javax.swing.text.DefaultFormatterFactory(new javax.swing.text.DateFormatter(new java.text.SimpleDateFormat("MM-dd-yy"))));

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 108, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 118, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(driverTF)
                    .addComponent(fromDateFTF, javax.swing.GroupLayout.DEFAULT_SIZE, 128, Short.MAX_VALUE))
                .addGap(18, 18, 18)
                .addComponent(getRecordsB)
                .addGap(73, 73, 73))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel2Layout.createSequentialGroup()
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(driverTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3)
                            .addComponent(fromDateFTF, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                    .addComponent(getRecordsB, javax.swing.GroupLayout.DEFAULT_SIZE, 51, Short.MAX_VALUE))
                .addContainerGap())
        );

        org.jdesktop.swingbinding.JTableBinding jTableBinding = org.jdesktop.swingbinding.SwingBindings.createJTableBinding(org.jdesktop.beansbinding.AutoBinding.UpdateStrategy.READ_WRITE, boundaryList, boundaryTable, "boundaryTableBinding");
        org.jdesktop.swingbinding.JTableBinding.ColumnBinding columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${id}"));
        columnBinding.setColumnName("Id");
        columnBinding.setColumnClass(Integer.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${endDate}"));
        columnBinding.setColumnName("End Date");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${boundary}"));
        columnBinding.setColumnName("Boundary");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${takenBoundary}"));
        columnBinding.setColumnName("Taken Boundary");
        columnBinding.setColumnClass(String.class);
        columnBinding = jTableBinding.addColumnBinding(org.jdesktop.beansbinding.ELProperty.create("${boundaryDeficit}"));
        columnBinding.setColumnName("Boundary Deficit");
        columnBinding.setColumnClass(String.class);
        bindingGroup.addBinding(jTableBinding);
        jTableBinding.bind();

        boundaryTable.addPropertyChangeListener(new java.beans.PropertyChangeListener() {
            public void propertyChange(java.beans.PropertyChangeEvent evt) {
                boundaryTablePropertyChange(evt);
            }
        });
        jScrollPane1.setViewportView(boundaryTable);

        jLabel2.setText("Total Deficit:");

        totalDeficitLabel.setText("N/A");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, 454, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(totalDeficitLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 102, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 438, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2)
                    .addComponent(totalDeficitLabel)))
        );

        jButton1.setText("Close");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        saveChangesB.setText("Save Changes");
        saveChangesB.setEnabled(false);
        saveChangesB.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveChangesBActionPerformed(evt);
            }
        });

        statusLabel.setFont(new java.awt.Font("Tahoma", 0, 12));
        statusLabel.setText(STATUS_MSG1);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(saveChangesB)
                        .addGap(38, 38, 38)
                        .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 106, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(126, 126, 126))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addContainerGap())))
            .addGroup(layout.createSequentialGroup()
                .addGap(18, 18, 18)
                .addComponent(statusLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 478, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, 27, Short.MAX_VALUE)
                    .addComponent(saveChangesB, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(statusLabel)
                .addContainerGap())
        );

        bindingGroup.bind();

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void driverTFActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_driverTFActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_driverTFActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.setVisible(false);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void getRecordsBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_getRecordsBActionPerformed
        String driver = driverTF.getText();
        String date = fromDateFTF.getText();
        if (!date.isEmpty()) {
            // format date for sql processing, assuming all dates are in 20xx year
            try {
                date = HelperUtil.formatDate("MM-dd-yy", "20yy-MM-dd", date);
            } catch (ParseException ex) {
                JOptionPane.showMessageDialog(this, "Invalid date input", "", JOptionPane.ERROR_MESSAGE);
            }
            System.out.println("Converted input to: " + date);
        }

        if (driver.isEmpty()) {
            JOptionPane.showMessageDialog(this, "Please fill both driver");
            return;
        }
        boundaryList.removeAll(boundaryList);
        try {
            boundaryList.addAll(operationsDAO.getOperationsFromDriverAndDate(driver, date));
        } catch (SQLException ex) {
            Logger.getLogger(BounderyUI.class.getName()).log(Level.SEVERE, null, ex);
            statusLabel.setText("Error Occurred: " + ex.getMessage());
        }
        saveChangesB.setEnabled(false);
        statusLabel.setText(STATUS_MSG2);
        updateTotalDeficitLabel();
    }//GEN-LAST:event_getRecordsBActionPerformed

    private void saveChangesBActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveChangesBActionPerformed
        if (boundaryTable.getCellEditor() != null) {
            boundaryTable.getCellEditor().stopCellEditing();
        }
        List<Operation> list = new LinkedList<Operation>();
        for (int i = 0; i < boundaryTable.getRowCount(); i++) {
            Operation o = new Operation();
            o.setId(Integer.parseInt(boundaryTable.getValueAt(i, 0).toString()));
            o.setEndDate(boundaryTable.getValueAt(i, 1).toString());
            o.setBoundary(boundaryTable.getValueAt(i, 2).toString());
            o.setTakenBoundary(boundaryTable.getValueAt(i, 3).toString());
            list.add(o);
        }
        try {
            operationsDAO.updateOperations(list);
            boundaryList.removeAll(boundaryList);
            boundaryList.addAll(list);
        } catch (SQLException ex) {
            Logger.getLogger(BounderyUI.class.getName()).log(Level.SEVERE, null, ex);
            statusLabel.setText("Error Occurred: " + ex.getMessage());
        }
        saveChangesB.setEnabled(false);
        statusLabel.setText("Changes Saved. " + STATUS_MSG1);
        updateTotalDeficitLabel();
    }//GEN-LAST:event_saveChangesBActionPerformed

    private void boundaryTablePropertyChange(java.beans.PropertyChangeEvent evt) {//GEN-FIRST:event_boundaryTablePropertyChange
        saveChangesB.setEnabled(true);
        statusLabel.setText(STATUS_MSG3);
    }//GEN-LAST:event_boundaryTablePropertyChange

 
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private java.util.List<Taxi.model.Operation> boundaryList;
    private javax.swing.JTable boundaryTable;
    private javax.swing.JTextField driverTF;
    private javax.swing.JFormattedTextField fromDateFTF;
    private javax.swing.JButton getRecordsB;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton saveChangesB;
    private javax.swing.JLabel statusLabel;
    private javax.swing.JLabel totalDeficitLabel;
    private org.jdesktop.beansbinding.BindingGroup bindingGroup;
    // End of variables declaration//GEN-END:variables


   /**
    * @param args the command line arguments
    */
    public static void main(String args[]) throws ClassNotFoundException, Exception {
        Properties dbProps = MenuUIGUI.load("db.properties");
        // initialize database
        Database.connectToDB(dbProps.getProperty("dburl"), dbProps.getProperty("uname")
                , dbProps.getProperty("passwd"));
        UIManager.setLookAndFeel(
                    UIManager.getSystemLookAndFeelClassName());
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                BounderyUI bounderyUI = new BounderyUI();
                bounderyUI.setLocationRelativeTo(null);
                bounderyUI.setVisible(true);
            }
        });
    }

    private void updateTotalDeficitLabel() {
        int total = 0;
        for (Operation operation : boundaryList) {
            total += Integer.parseInt(operation.getBoundaryDeficit());
        }
        this.totalDeficitLabel.setText(String.valueOf(total));
    }
}
